//
//  ComposePhotoViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-14.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "ComposePhotoViewController.h"
#import "UIImage+Additions.h"
#import "SearchResultView.h"
#import "SVProgressHUD.h"

@interface ComposePhotoViewController ()
{
    NSDictionary *selectedRow;
}

@end

@implementation ComposePhotoViewController

- (id)init
{
    self = [super initWithNibClass:[ComposePhotoViewController class]];
    if (self) {
        _dataSource = [[ComposePhotoDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"拍客广场"];
    
    UIImage *image = [_photoImage scaleForSize:_photoImageView.frame.size];
    self.photoImageView.image = image;
    
    [self.view addTarget:self action:@selector(tapGestureAction:)];
    [self reLayoutSubViews];
}

- (void)tapGestureAction:(UITapGestureRecognizer*)tapRecognizer
{
    if ([_descriptionTV resignFirstResponder]
        || [self.priceTF resignFirstResponder]
        || [self.shopNameTF resignFirstResponder]) {
        [self.theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.theScrollview setContentOffset:CGPointMake(0, 150) animated:YES];
}

- (IBAction)TextField_DidEndOnExit:(id)sender
{
    // 隐藏键盘.
    [sender resignFirstResponder];
    [self.theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self.theScrollview setContentOffset:CGPointMake(0, 50) animated:YES];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

- (IBAction)selPhotoTypeAction:(id)sender
{
    _envBtn.selected = _dishBtn.selected = NO;
    [sender setSelected:YES];
    
    [self reLayoutSubViews];
}

- (IBAction)searchShopAction:(id)sender
{
    SearchResultView *searchView = [[SearchResultView alloc] initWithKeyWord:_shopNameTF.text andDelegate:self];
    [searchView showWindow];
}

- (void)willShowWindow:(SearchResultView *)window
{
    [_shopNameTF resignFirstResponder];
    [self.theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)selectedRow:(NSDictionary *)row
{
    selectedRow = row;
    _shopNameTF.text = [row objectForKey:@"name"];
}

- (IBAction)postAction:(id)sender
{
    if (![self checkForm]) return;
    
    NSString *desc = _descriptionTV.text;
    NSString *price = _priceTF.text;
    NSString *shopId = [selectedRow objectForKey:@"id"];
    NSString *type = _dishBtn.selected ? @"2" : @"1";
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            type,@"type", price, @"price", desc, @"pingyu",shopId,@"id", nil];
    
    [_dataSource postPhoto:params];
    [SVProgressHUD show];
}

- (BOOL)checkForm
{
    if (!_dishBtn.selected && !_envBtn.selected) {
        [AppDelegate showMessage:@"请选择照片类型！"];
        return NO;
    }
    
    if (_descriptionTV.text.length == 0 || [_descriptionTV.text isEqualToString:@""]) {
        [AppDelegate showMessage:@"请填写评语！"];
        return NO;
    }
    
    if (_dishBtn.selected) {
        if (_priceTF.text.length == 0 || [_priceTF.text isEqualToString:@""]) {
            [AppDelegate showMessage:@"请填写菜品价格！"];
            return NO;
        }
    }
    
    if (_shopNameTF.text.length == 0 || [_shopNameTF.text isEqualToString:@""]) {
        [AppDelegate showMessage:@"请填写餐厅名称！"];
        return NO;
    }
    
    if (!selectedRow) {
        [AppDelegate showMessage:@"请填写餐厅名称并进行快速检索"];
        return NO;
    }
    
    return YES;
}

- (void)reLayoutSubViews
{
    [_shopNameTF leftMargin:5];
    
    _priceView.hidden = _envBtn.selected;
    [UIView drawBorders:@[_photoView, _descriptionTV, _priceView, _shopNameTF]];
    [UIView autoLayoutVertical:@[_topView,_descriptionTV, _priceView, _bottomView]];
    [_theScrollview autoHeight];
}

@end

//===============================================================================
#pragma ===================数据源类实现============================================
//===============================================================================

@implementation ComposePhotoDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
    }
    return self;
}

- (void)postPhoto:(NSDictionary *)params
{
    NSString *url = [NSString stringWithFormat:API_PHOTO_POST,[AppSetting userName]];
    [self post:url file:[AppSetting filePath:TempFile] extraParams:params];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@",request.responseString);
    
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    int state = [[data objectForKey:@"state"] intValue];
    if (state == 1) {
        [SVProgressHUD dismissWithSuccess:@"照片发布成功！"];
 
        self.viewController.parentVC.isBack = YES;
        [self.viewController.navigationController popViewControllerAnimated:YES];
    }
    
    if(state == 2) {
        [SVProgressHUD dismissWithError:@"照片发布失败！"];
    }
}

@end
